package Web;

import Bean.User;
import DAO.UserDAO;
import DAO.UserDAOImpl;
import service.UserService;
import service.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author jianjun
 * @Describe
 * @creat 2021-12-13-15:20
 */
public class RegistServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取请求的参数
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String email = request.getParameter("email");
        String code = request.getParameter("code");

        //2.检查验证码是否正确    先写死 --> 要求验证码为：abcde
        if ("abcde".equals(code)) {
            //3.检查用户名是否可用
            if (!userService.existsUsername(username)) {
                //可用,调用Service保存到数据库
                userService.registUser(new User(null, username, password, email));
                //跳到注册成功页面
                request.getRequestDispatcher("/pages/user/regist_success.jsp").forward(request,response);
            } else {
                System.out.println("用户名已存在");
                //表单错误，参数回显
                request.setAttribute("msg","用户名已存在");
                request.setAttribute("username",username);
                request.setAttribute("email",email);
                //不可用，跳转回注册页面
                request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
            }
        } else {
            System.out.println("验证码错误");
            //表单错误，参数回显
            request.setAttribute("msg","验证码错误");
            request.setAttribute("username",username);
            request.setAttribute("email",email);
            //不正确，跳回注册页面
            request.getRequestDispatcher("/pages/user/regist.jsp").forward(request,response);
        }
    }
}
